﻿using System;
using System.ComponentModel;
using System.Data;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using LifeInSharePoint.Common;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.WebPartPages;
using WebPart = System.Web.UI.WebControls.WebParts.WebPart;

namespace Metro.GridView.GridView
{
    [ToolboxItemAttribute(false)]
    public class GridView : Microsoft.SharePoint.WebPartPages.WebPart
    {

        #region private properties
        private bool _error = false;
        private DataTable sourceDataTable;
        private DataTableWrapper myDataTable;
        #endregion

        #region public properties

        public SPGridView oGrid;
        public string ConfiguredList { get; set; }
        public string ConfiguredContentTypes { get; set; }
        public string ConfiguredFields { get; set; }

        #endregion

        protected override void OnLoad(EventArgs e)
        {
            if (!_error)
            {
                try
                {
                    base.OnLoad(e);
                    this.EnsureChildControls();

                    string debug = SPQueryStringHelper.GetQueryStringItem(HttpContext.Current.Request.QueryString,
                                                                          "debug", String.Empty);
                    if (!string.IsNullOrEmpty(debug))
                    {
                        ConfiguredList = "";
                        ConfiguredContentTypes = "";
                        ConfiguredFields = "";
                    }

                    if (!string.IsNullOrEmpty(ConfiguredList) && !string.IsNullOrEmpty(ConfiguredContentTypes) && !string.IsNullOrEmpty(ConfiguredFields))
                    {
                        GenerateSPGridView();
                    }


                }
                catch (Exception ex)
                {
                    HandleException(ex);
                }
            }
        }

        /// <summary>
        /// Clear all child controls and add an error message for display.
        /// </summary>
        /// <param name="ex"></param>
        private void HandleException(Exception ex)
        {
            this._error = true;
            this.Controls.Clear();
            this.Controls.Add(new LiteralControl(ex.Message));
        }

        /// <summary>
        /// Create all your controls here for rendering.
        /// Try to avoid using the RenderWebPart() method.
        /// </summary>
        protected override void CreateChildControls()
        {

            if (!_error)
            {
                try
                {
                    base.CreateChildControls();
                    //GenerateSPGridView();
                    Button SaveValuesButton = new Button();
                    SaveValuesButton.Text = "Save Selected Values";
                    SaveValuesButton.Click += new EventHandler(SaveValuesButton_Click);
                    Controls.Add(SaveValuesButton);


                    Label lblConfiguredList = new Label();
                    lblConfiguredList.Text = ConfiguredList;
                    Controls.Add(lblConfiguredList);

                    Label lblConfiguredCT = new Label();
                    lblConfiguredCT.Text = ConfiguredContentTypes;
                    Controls.Add(lblConfiguredCT);

                    Label lblConfiguredFields = new Label();
                    lblConfiguredFields.Text = ConfiguredFields;
                    Controls.Add(lblConfiguredFields);
                }
                catch (Exception ex)
                {
                    HandleException(ex);
                }

            }



        }

        void SaveValuesButton_Click(object sender, EventArgs e)
        {
            this.Controls.Add(new LiteralControl("<br><br>Submit Pressed"));
            string str = string.Empty;

            string strjavascript = string.Empty;

            for (int idx = 0; idx < oGrid.Rows.Count; idx++)
            {

                CheckBox selectCtl = (CheckBox)oGrid.Rows[idx].FindControl("selectedTask");

                HtmlInputHidden taskIdCtl = (HtmlInputHidden)oGrid.Rows[idx].FindControl("taskIdItem");

                if (selectCtl.Checked && taskIdCtl.Value != String.Empty)
                {

                    //System.Windows.Forms.MessageBox.Show(taskIdCtl.Value.ToString());

                    str = str + taskIdCtl.Value.ToString();

                }
            }
            this.Controls.Add(new LiteralControl(str));
        }

        public override ToolPart[] GetToolParts()
        {
            CustomToolPart CustomToolPart_ = new CustomToolPart();
            CustomToolPart_.Title = "Custom Tool Part";

            ToolPart[] toolParts = new ToolPart[3];
            toolParts[0] = new WebPartToolPart();
            toolParts[1] = new CustomPropertyToolPart();
            toolParts[2] = CustomToolPart_;



            return toolParts;
        }

        private SPField getSPField(string Guid, SPList list)
        {
            SPField field = list.Fields[new Guid(Guid)];

            return field;
        }

        private void GenerateSPGridView()
        {
            if (!_error)
            {
                try
                {

                    SPList myList = SPContext.Current.Web.Lists.GetList(new Guid(ConfiguredList), true);
                    // get all the listitem
                    SPListItemCollection results = myList.Items;
                    // create the datatable object

                    sourceDataTable = new DataTable();
                    //Create Data Table Columns
                    sourceDataTable.Columns.Add("ID", typeof(int));

                    string[] Fields = ConfiguredFields.Split(new char[] { ';' });

                    int x = Fields.Length;
                    for (int i = 0; i < x; i++)
                    {
                        string[] Field = Fields[i].Split(new char[] { ',' });
                        SPField field = getSPField(Field[1], myList);

                        sourceDataTable.Columns.Add(field.InternalName, typeof(string));
                    }




                    // Create rows for each splistitem
                    DataRow row;

                    
                    

                    foreach (SPListItem result in results)
                    {
                        
                        row = sourceDataTable.Rows.Add();

                        //Add ID Column Data
                        SPField IDfield = getSPField("1d22ea11-1e32-424e-89ab-9fedbadb6ce1", myList);
                        GetRowValue(IDfield, row, result, myList);

                        for (int i = 0; i < x; i++)
                        {
                            string[] Field = Fields[i].Split(new char[] { ',' });
                            SPField field = getSPField(Field[1], myList);
                            GetRowValue(field, row, result, myList);
                        }
                    }

                    myDataTable = new DataTableWrapper(sourceDataTable);
                    Type t = myDataTable.GetType();

                    ObjectDataSource ds = new ObjectDataSource();
                    ds.ID = "myDataSource";
                    ds.TypeName = t.AssemblyQualifiedName;
                    ds.SelectMethod = "GetTable";
                    ds.ObjectCreating += new ObjectDataSourceObjectEventHandler(ds_ObjectCreating);
                    this.Controls.Add(ds);

                    this.oGrid = new SPGridView();
                    this.oGrid.ID = "oGridId";
                    this.oGrid.AutoGenerateColumns = false;

                    #region "Sorting"

                    oGrid.AllowSorting = true;


                    TemplateField selectTaskColumn = new TemplateField();

                    selectTaskColumn.HeaderText = "Select Task";

                    selectTaskColumn.ItemTemplate = new CustomSPGridViewTemplate(ListItemType.Item, "Select Task");

                    oGrid.Columns.Add(selectTaskColumn); 

                    for (int i = 0; i < x; i++)
                    {
                        string[] Field = Fields[i].Split(new char[] { ',' });
                        SPField field = getSPField(Field[1], myList);

                        GetBoundField(field, oGrid);
                    }

                    #endregion


                    #region "Filtering"

                    oGrid.AllowFiltering = true;


                    oGrid.DataSourceID = "myDataSource";
                    this.Controls.Add(oGrid);

                    #endregion


                    #region "Pagination"

                    //Note:Along with default pagination three other pagination models are given.
                    //Uncomment each pagination code one by one and check the different pagination models given. 

                    oGrid.PageSize = 5;
                    oGrid.AllowPaging = true;

                    //Default Pagination
                    oGrid.PageIndexChanging += new GridViewPageEventHandler(oGrid_PageIndexChanging);
                    oGrid.PagerTemplate = null;

                    #endregion

                    oGrid.RowDataBound +=new GridViewRowEventHandler(oGrid_RowDataBound);

                    oGrid.DataBind();
                }
                catch (Exception ex)
                {
                    HandleException(ex);
                }
            }
        }

        private void GetRowValue(SPField field, DataRow row, SPListItem _listItem, SPList myList)
        {
            SPFieldType fieldType = field.Type;
            string value = "";
            StringBuilder sb;
            switch (fieldType)
            {
                case SPFieldType.Integer:
                    value = Convert.ToString(SPListHelper.GetColumnIntValue(_listItem, field.InternalName));
                    break;
                case SPFieldType.Note:
                    value = SPListHelper.GetColumnStringValue(_listItem, field.InternalName);
                    break;
                case SPFieldType.DateTime:
                    SPFieldDateTime _DateTimeField = (SPFieldDateTime)field;
                    DateTime _date = (DateTime)SPListHelper.GetColumnValue(_listItem, field.InternalName);
                    if (_DateTimeField.DisplayFormat == SPDateTimeFieldFormatType.DateOnly)
                    {

                        value = _date.ToString(SPContext.Current.Web.Locale.DateTimeFormat.ShortDatePattern);
                    }
                    else
                    {
                        value = _date.ToString(SPContext.Current.Web.Locale.DateTimeFormat);
                    }

                    break;
                //case SPFieldType.Counter:
                //    break;
                //case SPFieldType.Choice:
                //    break;
                case SPFieldType.Lookup:
                    sb = new StringBuilder();
                    value = SPListHelper.GetColumnStringValue(_listItem, field.InternalName);
                    SPFieldLookup _LookupField = (SPFieldLookup)field;
                    if (_LookupField.AllowMultipleValues)
                    {
                        SPFieldLookupValueCollection _lookupValues = new SPFieldLookupValueCollection(value);
                        foreach (SPFieldLookupValue _lookupValue in _lookupValues)
                        {
                            sb.Append(string.Format("<a OnClick=\"OpenPopUpPage('/_layouts/listform.aspx?PageType=4&ListId={0}&ID={1}&RootFolder=*', RefreshPage); return false;\" href='/_layouts/listform.aspx?PageType=4&ListId={0}&ID={1}&RootFolder=*'>{2}</a>, ", _listItem.ParentList.ID, _lookupValue.LookupId, _lookupValue.LookupValue));
                        }
                    }
                    else
                    {
                        SPFieldLookupValue _lookupValue = new SPFieldLookupValue(value);
                        sb.Append(string.Format("<a OnClick=\"OpenPopUpPage('/_layouts/listform.aspx?PageType=4&ListId={0}&ID={1}&RootFolder=*', RefreshPage); return false;\" href='/_layouts/listform.aspx?PageType=4&ListId={0}&ID={1}&RootFolder=*'>{2}</a>, ", _listItem.ParentList.ID, _lookupValue.LookupId, _lookupValue.LookupValue));
                    }
                    value = sb.ToString().TrimEnd(',');

                    break;
                case SPFieldType.Boolean:
                    value = Convert.ToString(SPListHelper.GetColumnBoolValue(_listItem, field.InternalName));
                    break;
                case SPFieldType.Number:
                    value = SPListHelper.GetColumnStringValue(_listItem, field.InternalName);

                    SPFieldNumber _NumberField = (SPFieldNumber)field;
                    if (_NumberField.ShowAsPercentage)
                    {
                        value = (Convert.ToDouble(value) * 100) + "%";
                    }

                    break;
                //case SPFieldType.Currency:
                //    break;
                case SPFieldType.URL:
                    sb = new StringBuilder();                
                    value = SPListHelper.GetColumnStringValue(_listItem, field.InternalName);
                    SPFieldUrl _UrlField = (SPFieldUrl)field;
                    SPFieldUrlValue _UrlFieldValue = new SPFieldUrlValue(value);
                    if (_UrlField.DisplayFormat == SPUrlFieldFormatType.Hyperlink)
                    {                        
                        sb.Append(string.IsNullOrEmpty(_UrlFieldValue.Description)
                                      ? string.Format("<a href='{0}'>{0}</a>", _UrlFieldValue.Url)
                                      : string.Format("<a href='{0}'>{1}</a>", _UrlFieldValue.Url,
                                                      _UrlFieldValue.Description));
                    }
                    else
                    {
                        sb.Append(string.IsNullOrEmpty(_UrlFieldValue.Description)
                                      ? string.Format("<img src='{0}' border='0'/>", _UrlFieldValue.Url)
                                      : string.Format("<img src='{0}' alt='{1}'/>", _UrlFieldValue.Url,
                                                      _UrlFieldValue.Description));
                    }
                    value = sb.ToString();
                    break;
                //case SPFieldType.Computed:
                //    break;
                //case SPFieldType.Guid:
                //    break;
                //case SPFieldType.MultiChoice:
                //    break;
                //case SPFieldType.Calculated:
                //    break;
                //case SPFieldType.File:
                //    break;
                //case SPFieldType.Attachments:
                //    break;
                case SPFieldType.User:
                    SPFieldUser _UserField = (SPFieldUser)field;
                    string _stringValue = SPListHelper.GetColumnStringValue(_listItem, field.InternalName);
                    sb = new StringBuilder();
                    if (_UserField.AllowMultipleValues)
                    {
                        SPFieldUserValueCollection values = (SPFieldUserValueCollection)_listItem[field.InternalName];
                        foreach (SPFieldUserValue userVal in values)
                        {
                            SPUser user = userVal.User;
                            sb.Append(string.Format("<span><img border=\"0\" height=\"12\" src=\"/_layouts/images/imnhdr.gif\" onload=\"IMNRC('{0}')\" ShowOfflinePawn=\"1\" alt=\"\" id=\"user_presence_icon\"/></span>{1}", user.Email, user.LoginName));
                        }
                    }
                    else
                    {
                        SPFieldUser userField = (SPFieldUser)_listItem.Fields.GetField(field.InternalName);
                        SPFieldUserValue userVal =
                            (SPFieldUserValue)
                            userField.GetFieldValue(_stringValue);
                        SPUser user = userVal.User;
                        sb.Append(string.Format("<span><img border=\"0\" height=\"12\" src=\"/_layouts/images/imnhdr.gif\" onload=\"IMNRC('{0}')\" ShowOfflinePawn=\"1\" alt=\"\" id=\"user_presence_icon\"/></span>{1}", user.Email, user.LoginName));
                    }
                    value = sb.ToString();
                    break;
                default:
                    value = SPListHelper.GetColumnStringValue(_listItem, field.InternalName);
                    break;
            }
            row[field.InternalName] = value;
        }

        private void GetBoundField(SPField field, SPGridView oGrid)
        {
            SPFieldType fieldType = field.Type;
            string value = "";
            switch (fieldType)
            {
                case SPFieldType.User:
                case SPFieldType.Lookup:
                case SPFieldType.Note:
                case SPFieldType.URL:
                    TemplateField htmlColumn = new TemplateField();
                    htmlColumn.HeaderText = field.Title;
                    htmlColumn.SortExpression = field.InternalName;
                    htmlColumn.ItemTemplate = new TemplatedHTMLControl(field.InternalName);
                    oGrid.Columns.Add(htmlColumn);
                    break;
                default:
                    BoundField col = new BoundField();
                    col.HeaderText = field.Title;
                    col.DataField = field.InternalName;
                    col.SortExpression = field.InternalName;
                    oGrid.Columns.Add(col);
                    break;
            }

        }

        void oGrid_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            oGrid.PageIndex = e.NewPageIndex;
            oGrid.DataBind();
        }

        private void oGrid_RowDataBound(object sender, GridViewRowEventArgs e)
        {

            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                HtmlInputHidden itemId = (HtmlInputHidden)e.Row.FindControl("taskIdItem");
                if (itemId != null)
                {
                    DataRowView data = (DataRowView)e.Row.DataItem;
                    itemId.Value = data["ID"].ToString();
                }
            }

        } 

        void ds_ObjectCreating(object sender, ObjectDataSourceEventArgs e)
        {
            myDataTable = new DataTableWrapper(sourceDataTable);
            e.ObjectInstance = myDataTable;
        }
    }
}
